<?php

namespace App\Http\Controllers\Admin;

use App\Models\AccessNum;
use App\Models\Activity;
use App\Models\ActivityApply;
use App\Models\ActivityType;
use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityDatabase;
use App\Models\CompetiteActivityWorks;
use App\Models\OtherAccessNum;
use App\Models\ReadingTask;
use App\Models\ReadingTaskAppointUser;
use App\Models\ReadingTaskExecute;
use App\Models\RecommendUser;
use App\Models\Survey;
use App\Models\UserInfo;
use Illuminate\Support\Facades\DB;

/**
 * 整个项目 数据分析
 * Class AnswerType
 * @package app\admin\controller
 */
class DataAnalysisController extends CommonController
{


    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 小程序访问统计
     * @param  $start_time 开始时间 不传，默认是当天
     * @param  $end_time 结束时间 不传，默认是当天
     */
    public function appletStatistics()
    {
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        //默认当日
        if (empty($start_time) || empty($end_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }

        //获取注册人数
        $userInfoModel = new UserInfo();
        //注册人数
        $data['register_number'] = $userInfoModel->getUserNumber(1, $start_time, $end_time);
        //绑定读者证数量
        $data['bind_number'] = $userInfoModel->getUserNumber(2, $start_time, $end_time);

        $otherAccountNumModel = new OtherAccessNum();
        //数字资源点击量
        $data['digital_number'] = $otherAccountNumModel->getClickNumber(1, $start_time, $end_time);
        //重图到家点击量
        //    $data['go_home_number'] = $otherAccountNumModel->getClickNumber(2, $start_time, $end_time);

        //注册人数统计(折线图)
        $data['register_statistics'] = $userInfoModel->registerStatistics($start_time, $end_time);
        $data['register_statistics'] = self::disCartogramDayOrHourData($data['register_statistics'], null, $start_time, $end_time, 'times', 'number');
        //数字资源点击量统计(折线图)
        $data['digital_click_statistics'] = $otherAccountNumModel->clickStatistics(1, $start_time, $end_time);
        $data['digital_click_statistics'] = self::disCartogramDayOrHourData($data['digital_click_statistics'], null, $start_time, $end_time, 'times', 'number');

        //重图到家点击量统计(折线图)
        // $data['go_home_click_statistics'] = $otherAccountNumModel->clickStatistics(2, $start_time, $end_time);
        // $data['go_home_click_statistics'] = self::disCartogramDayOrHourData($data['go_home_click_statistics'], null, $start_time, $end_time, 'times', 'number');


        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 小程序访问总统计图
     * @param year   年  例如  2022   2021
     * @param month  月份  1,2,3,4,5   默认 空 按年筛选
     */
    public function accessStatistics()
    {
        $year = request()->year;
        $month = request()->month;

        if (empty($year)) {
            $year = date('Y');
        }

        list($start_time, $end_time) = get_start_end_time_by_year_month($month, $year);

        $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time));

        //访问人数
        $accessNumModel = new AccessNum();
        $get_access_statistics = $accessNumModel->getAccessStatistics($start_time, $end_time, empty($month) ? 1 : 2);

        $data = self::disCartogramDayOrHourData($get_access_statistics, empty($month) ? $year : null, $start_time, $end_time, 'times');

        $data['access_total_number'] = $accessNumModel->getAccessNumber();
        $data['access_number'] = $accessNumModel->getAccessNumber($start_time, $end_time);

        return $this->returnApi(200, "查询成功", true, $data);
    }

    /**
     * 活动参与人数统计
     * @param  $start_time 开始时间 不传，默认是当天
     * @param  $end_time 结束时间 不传，默认是当天
     */
    public function activityStatistics()
    {
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        //默认当日
        if (empty($start_time) || empty($end_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }
        $actTypeModel = new ActivityType();
        //活动类型分布统计
        $data['act_type_statistics'] = $actTypeModel->actTypeStatistics($start_time, $end_time);

        $actApplyModel = new ActivityApply();
        //重图到家点击量统计(折线图)
        $data['apply_statistics'] = $actApplyModel->applyStatistics(null, $start_time, $end_time);
        $data['apply_statistics'] = self::disCartogramDayOrHourData($data['apply_statistics'], null, $start_time, $end_time, 'times', 'number');
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 荐购、问卷统计
     */
    public function recomAndSurveyStatistics()
    {
        // $recommendUserModel = new RecommendUser();
        // $data['recom_person'] = $recommendUserModel->recomPerson(); //荐购人次
        // $data['recom_number'] = $recommendUserModel->recomNumber(); //荐购数量

        // $surveyModel = new Survey();
        // $data['survey_number'] = $surveyModel->surveyNumber(); //问卷数量
        // $data['survey_person'] = $surveyModel->surveyPerson(); //参与人数

        // return $this->returnApi(200, "获取成功", true, $data);
    }


    /**
     * 用户授权注册总统计图
     * @param year   年  例如  2022   2021
     * @param month  月份  1,2,3,4,5   默认 空 按年筛选
     */
    public function authRegisterStatistics()
    {
        $year = request()->year;
        $month = request()->month;

        if (empty($year)) {
            $year = date('Y');
        }

        list($start_time, $end_time) = get_start_end_time_by_year_month($month, $year);

        $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time));

        //访问人数
        $userInfoModel = new UserInfo();
        $get_access_statistics = $userInfoModel->registerStatistics($start_time, $end_time, empty($month) ? 1 : 2);

        $data = self::disCartogramDayOrHourData($get_access_statistics, empty($month) ? $year : null, $start_time, $end_time, 'times', 'number');

        $data['register_total_number'] = $userInfoModel->getRegisterNumber();
        $data['register_number'] = $userInfoModel->getRegisterNumber($start_time, $end_time);

        return $this->returnApi(200, "查询成功", true, $data);
    }


    /**
     * 其他数据统计
     */
    public function otherStatistics()
    {
        //发布活动总数
        $data['activity'] = Activity::where('is_del', 1)->count();
        //活动报名总数
        $data['activity_apply'] = ActivityApply::whereIn('status', [1, 3, 4])->count();
        //发布大赛活动总数
        $data['competite_activity'] = CompetiteActivity::where('is_del', 1)->count();
        //大赛活动投递作品总数
        $data['competite_activity_works'] = CompetiteActivityWorks::whereIn('status', [1, 2, 3])->count();
        //大赛活动作品点赞总数
        //大赛活动投递作品总数
        $data['competite_activity_vote'] = CompetiteActivityWorks::where('status', 1)->sum('vote_num');
        //发布任务量
        $data['reading_task'] =  ReadingTask::where('is_del', 1)->count();
        //完成任务用户数
        $data['reading_task_execute'] =  ReadingTaskExecute::where('progress', '100')->count();

        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 征集活动作品大类型统计
     * @param con_id   征集id
     */
    public function competiteActivityStatistics()
    {

        $con_id = request()->con_id;

        $competiteActivityModel = new CompetiteActivity();
        //征集活动统计
        $data['competite_activity_works_statistics'] = $competiteActivityModel->competiteActivityStatistics($con_id);
        return $this->returnApi(200, "获取成功", true, $data);
    }
    /**
     * 征集活动活动投递人次
     * @param year   年  例如  2022   2021
     * @param month  月份  1,2,3,4,5   默认 空 按年筛选
     */
    public function competiteActivityPersonStatistics()
    {
        $year = request()->year;
        $month = request()->month;

        if (empty($year)) {
            $year = date('Y');
        }

        list($start_time, $end_time) = get_start_end_time_by_year_month($month, $year);

        $start_time = date('Y-m-01 00:00:00', strtotime($start_time)); //固定下开始时间
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time)); //固定下结束时间

        $competiteActivityWorksModel = new CompetiteActivityWorks();
        //投递活动人次
        $condition[] = [DB::raw("status in (1,2,3)"), '1']; //后面 1 无任何意义
        $data['works_statistics'] = $competiteActivityWorksModel->timesStatistics($year, $month, $start_time, $end_time, 'create_time', 'id', null, $condition);
        //投递活动人次总数
        $data['works_total_number'] = $competiteActivityWorksModel->totalNumberStatistics($start_time, $end_time, 'create_time', 'id', null, $condition);

        return $this->returnApi(200, "查询成功", true, $data);
    }


    /**
     * 数据库作品统计
     */
    public function databaseWorksStatistics()
    {
        $competiteActivityDatabaseModel = new CompetiteActivityDatabase();
        //数据库作品统计
        $res = $competiteActivityDatabaseModel->databaseWorksStatistics();
        $data['database_works_statistics'] = $res['data'];
        $data['database_works_total_number'] = $res['total'];
        //数据库作品类型
        list($data['database_works_number'], $data['database_ebook_number']) = $competiteActivityDatabaseModel->databaseWorksTypeStatistics();

        return $this->returnApi(200, "查询成功", true, $data);
    }

    /**
     * 用户统计
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(类型标签)
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序  3 报名活动场次  4 征集活动场次  5 完成任务数
     */
    public function userStatistics()
    {
        $page = intval($this->request->page) ?: 1;
        $limit = intval($this->request->limit) ?: 10;
        $keywords = $this->request->keywords;
        $sort = $this->request->input('sort', 1);

        $userInfoModel = new UserInfo();
        $res = $userInfoModel->userStatistics($keywords, $sort, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['per_page'] = $limit;
        $res['current_page'] = $page;
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 单个用户统计
     * @param user_id int 用户id
     */
    public function singleUserStatistics()
    {
        $user_id = $this->request->user_id;
        if (empty($user_id)) {
            return $this->returnApi(201, "参数错误");
        }
        $activityApplyModel = new ActivityApply();
        $competiteActivityWorksModel = new CompetiteActivityWorks();
        $readingTaskExecuteModel = new ReadingTaskExecute();

        $res['activty_number'] = $activityApplyModel->getUserApplyNumber($user_id);
        $activty_type_info = $activityApplyModel->userApplyTypeStatistics($user_id); //活动类型统计数据
        $res['activty_type_info'] = $activty_type_info; //参加活动分布图
        $res['activty_type_like'] = !empty($activty_type_info[0]['type_name']) ? $activty_type_info[0]['type_name'] : null;

        $res['competite_activty_number'] = $competiteActivityWorksModel->getUserApplyNumber($user_id);
        $competite_activty_type_info = $competiteActivityWorksModel->userApplyTypeStatistics($user_id); //征集活动类型统计数据
        $res['competite_activty_type_info'] = $competite_activty_type_info; //参加征集活动分布图
        $res['competite_activty_type_like'] = !empty($competite_activty_type_info[0]['type_name']) ? $competite_activty_type_info[0]['type_name'] : null;

        $readingTaskAppointUserModel = new ReadingTaskAppointUser();
        $appoint_user_number = $readingTaskAppointUserModel->getUserReadingTaskNumebr($user_id); //阅读任务总数量
        $res['reading_task_finished_number'] = $readingTaskExecuteModel->userReadingTaskProgress(null, $user_id); //已完成阅读数量
        if (!empty($appoint_user_number)) {
            $res['reading_task_number'] = $appoint_user_number; //阅读任务总数量
            $res['reading_task_finished_progress'] =  $appoint_user_number ? sprintf("%.2f", $res['reading_task_finished_number'] / $appoint_user_number * 100) : 0;
        } else {
            $res['reading_task_number'] = 0; //阅读任务总数量
            $res['reading_task_finished_progress'] =  0;
        }

        //获取阅读任务
        $res['reading_task_unfinished_number'] = $readingTaskExecuteModel->userReadingTaskProgress(null, $user_id); //未完成阅读数量
        $res['reading_task_unread_number'] = $readingTaskExecuteModel->userReadingTaskUnreadNumber($user_id, $res['reading_task_finished_number'] + $res['reading_task_unfinished_number']); //未阅读数量

        return $this->returnApi(200, "查询成功", true, $res);
    }
}
